<?php
/**
 * Created by PhpStorm.
 * User: Xavier Yang
 * Date: 2018/12/30
 * Time: 16:46
 * Email:499873958@qq.com
 */

namespace Xavier\Swoole\Parse;

use Xavier\Facade\Config;
use Xavier\Facade\Container;

trait Parse
{
    public function run($method, $url)
    {
        $dispatcher = Container::get(\FastRoute\Dispatcher\GroupCountBased::class);
        $routeInfo  = $dispatcher->dispatch($method, $url);
        switch ($routeInfo[0]) {
            case FastRoute\Dispatcher::NOT_FOUND:
                // ... 404 Not Found
                return [
                    "code" => 404,
                ];
            case FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
                // ... 405 Method Not Allowed
                return [
                    "code" => 405,
                ];
                break;
            case FastRoute\Dispatcher::FOUND:
                $handler = $routeInfo[1];
                $vars    = $routeInfo[2];//get
                return [
                    "code"    => 200,
                    "handler" => $handler,
                    "get"     => $vars,
                ];
                break;
        }

    }

    /**
     * @param $url
     */
    public function parseHandle($url)
    {
        //格式 \\命名空间@方法
        $routers = explode("@", $url);
        $check   = is_array($routers) && count($routers) == 2;
        $class   = $check ? $routers[0] : $url;
        $action  = Config::get("default_action")??"index";
        $action  = $check ? $routers[1] : $action;
        if (class_exists($class)) {
            return [
                "class"=>$class,
                "action"=>$action
            ];
        }
        return false;
    }

}